import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:grint/entity/comment.dart';
import 'package:grint/utils/local_store.dart';
import 'dart:convert';

class CommentState {
  final List<Comment> comments;
  final bool isLoading;
  final String? errorMessage;

  const CommentState({
    this.comments = const [],
    this.isLoading = false,
    this.errorMessage,
  });

  CommentState copyWith({
    List<Comment>? comments,
    bool? isLoading,
    String? errorMessage,
  }) {
    return CommentState(
      comments: comments ?? this.comments,
      isLoading: isLoading ?? this.isLoading,
      errorMessage: errorMessage,
    );
  }
}

class CommentCubit extends Cubit<CommentState> {
  final LocalStore _localStore = LocalStore();

  CommentCubit() : super(const CommentState());

  Future<void> loadComments(String submissionId) async {
    emit(state.copyWith(isLoading: true, errorMessage: null));

    try {
      final commentsJson = _localStore.getTextValue(
        'comments_$submissionId',
        defaultValue: '[]',
      );
      final List<dynamic> commentsList = jsonDecode(commentsJson);

      final comments =
          commentsList.map((json) => Comment.fromJson(json)).toList()
            ..sort((a, b) => b.createdAt.compareTo(a.createdAt));

      emit(state.copyWith(comments: comments, isLoading: false));
    } catch (e) {
      emit(
        state.copyWith(
          isLoading: false,
          errorMessage: 'Failed to load comments: $e',
        ),
      );
    }
  }

  Future<bool> addComment({
    required String submissionId,
    required String userId,
    required String userName,
    required String userAvatar,
    required String content,
  }) async {
    try {
      final commentId = 'comment_${DateTime.now().millisecondsSinceEpoch}';
      final newComment = Comment(
        commentId: commentId,
        shareId: submissionId,
        userId: userId,
        userName: userName,
        userAvatar: userAvatar,
        content: content,
        createdAt: DateTime.now(),
      );

      // 获取现有评论
      final commentsJson = _localStore.getTextValue(
        'comments_$submissionId',
        defaultValue: '[]',
      );
      final List<dynamic> commentsList = jsonDecode(commentsJson);

      // 添加新评论
      commentsList.add(newComment.toJson());

      // 保存到本地存储
      await _localStore.setTextValue(
        'comments_$submissionId',
        jsonEncode(commentsList),
      );

      // 更新状态
      final updatedComments = [newComment, ...state.comments];
      emit(state.copyWith(comments: updatedComments));

      return true;
    } catch (e) {
      emit(state.copyWith(errorMessage: 'Failed to add comment: $e'));
      return false;
    }
  }

  Future<bool> deleteComment(String commentId, String submissionId) async {
    try {
      final commentsJson = _localStore.getTextValue(
        'comments_$submissionId',
        defaultValue: '[]',
      );
      final List<dynamic> commentsList = jsonDecode(commentsJson);

      commentsList.removeWhere((json) => json['commentId'] == commentId);

      await _localStore.setTextValue(
        'comments_$submissionId',
        jsonEncode(commentsList),
      );

      final updatedComments =
          state.comments.where((c) => c.commentId != commentId).toList();
      emit(state.copyWith(comments: updatedComments));

      return true;
    } catch (e) {
      emit(state.copyWith(errorMessage: 'Failed to delete comment: $e'));
      return false;
    }
  }

  void clearError() {
    emit(state.copyWith(errorMessage: null));
  }
}
